package com.example.water_quality_analysis.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.water_quality_analysis.pojo.model.Data;
import com.example.water_quality_analysis.handler.GlobalExceptionHandler;
import com.example.water_quality_analysis.pojo.model.WaterQuality;
import com.example.water_quality_analysis.pojo.model.WaterQualityYear;
import com.example.water_quality_analysis.pojo.vo.WaterDailyQuality;
import com.example.water_quality_analysis.pojo.vo.WaterDailyQualityYear;
import com.example.water_quality_analysis.service.DataService;
import com.example.water_quality_analysis.mapper.DataMapper;
import com.opencsv.CSVReader;
import com.opencsv.exceptions.CsvException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.*;
import java.time.temporal.TemporalAdjusters;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * @author lin
 * @description 针对表【data】的数据库操作Service实现
 * @createDate 2024-07-02 15:57:43
 */
@Service
public class DataServiceImpl extends ServiceImpl<DataMapper, Data> implements DataService {
    @Autowired
    private DataMapper dataMapper;

    private final static Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    @Override
    public void getDataFromFile() throws IOException, CsvException, ParseException {
        String filePath = "src/main/resources/data.csv";
        CSVReader reader = new CSVReader(new InputStreamReader(new FileInputStream(filePath), StandardCharsets.UTF_8));
        List<String[]> allData = reader.readAll();
        // Read the header row to map the columns
        String[] header = allData.get(0);
        logger.info("CSV Header: ");
        for (String column : header) {
            logger.info(column);
        }
        for (int i = 1; i < allData.size(); i++) { // Skip header row
            String[] row = allData.get(i);
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date date = dateFormat.parse(row[headerIndex(header, "监测时间")]);

            dataMapper.addDataByFile(1L, 1L, date, parseDouble(row[headerIndex(header, "pH")]), parseDouble(row[headerIndex(header, "氨氮")]), parseDouble(row[headerIndex(header, "总磷")]), parseDouble(row[headerIndex(header, "总氮")]), parseDouble(row[headerIndex(header, "水温")]), parseDouble(row[headerIndex(header, "溶解氧")]), parseDouble(row[headerIndex(header, "高锰酸钾")]), parseDouble(row[headerIndex(header, "电导率")]), parseDouble(row[headerIndex(header, "浊度")]));
        }
    }

//    @Deprecated(
//            since = "2024-10-06",
//            forRemoval = true
//    )


    @Override
    public WaterDailyQuality analysisDailyData(Long page, Long size) {
        // 分页逻辑
        Page<WaterQuality> Page = new Page<>(page, size);

        // 执行SQL查询，获取聚合后的水质数据
        Page<WaterQuality> waterQualityPage = dataMapper.getAggregatedWaterQuality(Page); // 使用分页进行查询

        if (waterQualityPage == null || waterQualityPage.getRecords() == null || waterQualityPage.getRecords().isEmpty()) {
            return null; // 或返回空的WaterDailyQuality对象
        }

        WaterDailyQuality waterDailyQuality = new WaterDailyQuality();
        waterDailyQuality.setPageSize(waterQualityPage.getSize());
        waterDailyQuality.setAllRecordNum(waterQualityPage.getTotal());
        waterDailyQuality.setCurrentPage(waterQualityPage.getCurrent());
        waterDailyQuality.setAllPages(waterQualityPage.getPages());
        waterDailyQuality.setRecords(waterQualityPage.getRecords());

        return waterDailyQuality;
    }


    @Override
    public WaterDailyQuality analysisMonthlyData(Long page, Long size) {
        // 分页逻辑
        Page<WaterQuality> Page = new Page<>(page, size);

        // 执行SQL查询，获取聚合后的水质数据，按年和月分组
        Page<WaterQuality> waterQualityPage = dataMapper.getAggregatedMonthlyWaterQuality(Page); // 使用分页进行查询

        if (waterQualityPage == null || waterQualityPage.getRecords() == null || waterQualityPage.getRecords().isEmpty()) {
            return null; // 或返回空的WaterDailyQuality对象
        }

        WaterDailyQuality waterMonthlyQuality = new WaterDailyQuality();
        waterMonthlyQuality.setPageSize(waterQualityPage.getSize());
        waterMonthlyQuality.setAllRecordNum(waterQualityPage.getTotal());
        waterMonthlyQuality.setCurrentPage(waterQualityPage.getCurrent());
        waterMonthlyQuality.setAllPages(waterQualityPage.getPages());
        waterMonthlyQuality.setRecords(waterQualityPage.getRecords());

        return waterMonthlyQuality;
    }

    @Override
    public WaterDailyQualityYear analysisYearlyData(Long page, Long size) {
        // 分页逻辑
        Page<WaterQualityYear> Page = new Page<>(page, size);
        Page<WaterQualityYear> waterQualityPage = dataMapper.getAggregatedYearlyWaterQuality(Page); // 使用分页进行查询

        if (waterQualityPage == null || waterQualityPage.getRecords() == null || waterQualityPage.getRecords().isEmpty()) {
            return null; // 或返回空的WaterDailyQuality对象
        }

        WaterDailyQualityYear waterYearlyQuality = new WaterDailyQualityYear();
        waterYearlyQuality.setPageSize(waterQualityPage.getSize());
        waterYearlyQuality.setAllRecordNum(waterQualityPage.getTotal());
        waterYearlyQuality.setCurrentPage(waterQualityPage.getCurrent());
        waterYearlyQuality.setAllPages(waterQualityPage.getPages());
        waterYearlyQuality.setRecords(waterQualityPage.getRecords());

        return waterYearlyQuality;
    }


    @Override
    public WaterQuality analysisDayData(LocalDate day) {
        return dataMapper.getWaterQualityByDay2(day);
    }

    @Override
    public WaterQuality analysisMonthData(LocalDate month) {
        LocalDate monthStart = month.with(TemporalAdjusters.firstDayOfMonth()); // 获取当月第一天
        LocalDate monthEnd = month.with(TemporalAdjusters.lastDayOfMonth()); // 获取当月最后一天
        return dataMapper.getWaterQualityByMonths2(monthStart, monthEnd);
    }


    @Override
    public WaterQuality analysisYearData(LocalDate year) {
        LocalDate yearStart = year.with(TemporalAdjusters.firstDayOfYear()); // 获取当年第一天
        LocalDate yearEnd = year.with(TemporalAdjusters.lastDayOfYear()); // 获取当年最后一天
        return dataMapper.getWaterQualityByYear2(yearStart, yearEnd);
    }


    private int headerIndex(String[] header, String columnName) {
        for (int i = 0; i < header.length; i++) {
            if (header[i].equals(columnName)) {
                return i;
            }
        }
        throw new IllegalArgumentException("Column not found: " + columnName);
    }

    private Double parseDouble(String value) {
        try {
            return Double.parseDouble(value);
        } catch (NumberFormatException e) {
            return null;
        }
    }

}




